import {AsyncStorage} from 'react-native';
export const BaseUrl = 'https://market.51bills.cn'

export default class DataStore {
     /**
     * 获取数据，优先获取本地数据，如果无本地数据或本地数据过期则获取网络数据
     * @param url //path路径
     * @param data //传递的参数
     * @param type //请求的类别
     * @param AsyncDataName //缓存到本地名字 --- 唯一
     * @param isJson //是否为json类型的数据
     * @returns {Promise}
     */
    fetchData(url = '',data = {}, type = 'GET',AsyncDataName='',isJson=true,needRefresh=false) {
        url = BaseUrl + url;
        return new Promise((resolve, reject) => {
            this.fetchLocalData(url+AsyncDataName).then((wrapData) => {
                if (!needRefresh && wrapData && DataStore.checkTimestampValid(wrapData.timestamp)) {
                    resolve(wrapData);
                } else {
                    this.FetchNetData(url,data,type,AsyncDataName,isJson).then((data) => {
                        resolve(this._wrapData(data));
                    }).catch((error => {
                        reject(error);
                    }))
                }
            }).catch((error) => {
                this.FetchNetData(url,data,type,AsyncDataName,isJson).then((data) => {
                    resolve(this._wrapData(data));
                }).catch((error => {
                    reject(error);
                }))
            })
        })
    }
    /**
     * 获取网路数据;
     * @param url //url路径
     * @param data //参数
     * @param type //请求类型
     * @param AsyncDataName //储存数据的名称
     * @param isJson //是否为json格式
     */
    FetchNetData(url,data,type,AsyncDataName,isJson=true){
        type = type.toUpperCase();
        if(type == 'GET'){
            let dataStr = '' //拼接字符串
            Object.keys(data).forEach(key=>{
                dataStr += key + '=' + data[key] + '&';
            })
            if(dataStr !== ""){
                dataStr = dataStr.substr(0,dataStr.lastIndexOf('&'));
                url = url + '?' + dataStr;
            }
        }
        let request = {},body = new FormData(),headers = new Headers();
        let requestConfig = {
            method:type,
            cache:'force-cache',
        }
        if( type == 'POST'){ 
            if(isJson){
                headers.append('content-type', 'application/json;charset=UTF-8');
                body = JSON.stringify(data);
            }else{
                for(let i in data) {
                    body.append(i, data[i])
                };
            }
            request = Object.assign(requestConfig,{headers,body});
        }
        return new Promise((resolve, reject) => {
            fetch(url,request)
                    .then((response) => {
                        if (response.ok) {
                            return response.json()
                        }
                        throw new Error('Network response was not ok.');
                    })
                    .then((responseData) => {
                        AsyncDataName && this.saveData(url+AsyncDataName,responseData) //保存数据 =>  为url加上AsyncDataName
                        // console.log(responseData)
                        resolve(responseData);
                    })
                    .catch((error) => {
                        reject(error);
                    })
        })
    }
    
    /**
     * 获取本地数据
     * @param url //name名称
     * @returns {Promise}
     */
    fetchLocalData(url) {
        return new Promise((resolve, reject) => {
            AsyncStorage.getItem(url,(error,result)=>{
                if(!error){
                    try {
                        resolve(JSON.parse(result));
                    } catch (e) {
                        reject(e);
                        console.log(e)
                    }
                }else{
                    reject(error);
                    console.log(error);
                }
            })
        })
    };
    /**
     * 保存数据
     * @param url
     * @param data
     * @param callback
     */
    saveData(url, data, callback) {
        if (!data || !url) return;
        AsyncStorage.setItem(url, JSON.stringify(this._wrapData(data)), callback);
    };
    /**
     * 清除本地数据
     * @param {name} string
     */
    removeLocaData(name,callback){
        if(!name) return;
        AsyncStorage.removeItem(name,callback);
    }
    /**
     * 给data增加时间
     * @param data
     */
    _wrapData(data) {
        return {data: data, timestamp: new Date().getTime()};
    };
    /**
     * 检查timestamp是否在有效期内
     * @param timestamp 项目更新时间
     * @return {boolean} true 不需要更新,false需要更新
     */
    static checkTimestampValid(timestamp) {
        if(!timestamp){return false};
        const currentDate = new Date();
        const targetDate = new Date();
        targetDate.setTime(timestamp);
        if (currentDate.getMonth() !== targetDate.getMonth()) return false;
        if (currentDate.getDate() !== targetDate.getDate()) return false;
        if (currentDate.getHours() - targetDate.getHours() > 4) return false;//有效期4个小时
        // if (currentDate.getMinutes() - targetDate.getMinutes() > 1)return false;
        return true;
    }
}